package model

import "github.com/zeromicro/go-zero/core/stores/mon"
import "context"
import 	"go.mongodb.org/mongo-driver/bson"

var _ DcoResultModel = (*customDcoResultModel)(nil)

type (
	// DcoResultModel is an interface to be customized, add more methods here,
	// and implement the added methods in customDcoResultModel.
	DcoResultModel interface {
		dcoResultModel
		FindOneByCID(ctx context.Context, cid string) (*DcoResult, error)

		InsertOrUpdate(ctx context.Context, data *DcoResult) error
	}

	customDcoResultModel struct {
		*defaultDcoResultModel
	}
)

// NewDcoResultModel returns a model for the mongo.
func NewDcoResultModel(url, db, collection string) DcoResultModel {
	conn := mon.MustNewModel(url, db, collection)
	return &customDcoResultModel{
		defaultDcoResultModel: newDefaultDcoResultModel(conn),
	}
}

func (m *customDcoResultModel) FindOneByCID(ctx context.Context, cid string) (*DcoResult, error) {

	var data DcoResult

	err := m.conn.FindOne(ctx, &data, bson.M{"cid": cid})
	switch err {
	case nil:
		return &data, nil
	case mon.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (m *customDcoResultModel) InsertOrUpdate(ctx context.Context, data *DcoResult) error {

	d, err := m.FindOneByCID(ctx, data.CID)
	if err != nil {
		if err == ErrNotFound {
			err = m.Insert(ctx, data)
		}
		return err
	} else {
		d.Result = data.Result
		_, err = m.Update(ctx, d)
	}
	return err
}
